import { Component, OnInit } from '@angular/core';
import { HttpService } from '../../service/http.service';
import { HttpRouterService } from '../../service/http-router.service';
import { StorageService } from '../../service/storage.service';
import { Router } from '@angular/router';
import _ from 'underscore';


@Component({
  selector: 'app-preference',
  templateUrl: './preference.component.html',
  styleUrls: ['./preference.component.less']
})
export class PreferenceComponent implements OnInit {

  public preference = {
    housetype: '',
    cartype: '',
    accumulationfund: '',
    socialsecurity: ''
  };
  public oldSetting = '';
  public newSetting = '';

  constructor(
              private _http: HttpService,
              private _storage: StorageService,
              private _httpRouter: HttpRouterService,
              private _router: Router
  ) { }

  ngOnInit() {
    if (this._storage.getSession('token') ? true : false) {
      const userToken = 'token=' + this._storage.getSession('token');
      this._http.post(this._httpRouter.getUser, userToken).then( res => {
        if (res.code === 1) {
          this.preference.housetype = res.data.housetype || '';
          this.preference.cartype = res.data.cartype || '';
          this.preference.accumulationfund = res.data.accumulationfund || '';
          this.preference.socialsecurity = res.data.socialsecurity || '';
          this.oldSetting = 'cartype=' + res.data.cartype
                   +  '&housetype=' + res.data.housetype
                   +  '&accumulationfund=' + res.data.accumulationfund
                   +  '&socialsecurity=' + res.data.socialsecurity;
        }
      });
    }else {
      alert('请登录后再设置您的个人偏好');
      return;
    }

  }

  saveSetting() {
    this.newSetting = 'cartype=' + this.preference.cartype
                     + '&housetype=' + this.preference.housetype
                     + '&accumulationfund=' + this.preference.accumulationfund
                     + '&socialsecurity=' + this.preference.socialsecurity;

    const param = 'token=' + this._storage.getSession('token') + '&' + this.newSetting;
      if (param === 'token=' + this._storage.getSession('token') + '&' + this.oldSetting) {
        this._router.navigate(['/attache/personal']);
      }else {
        this._http.post(this._httpRouter.edit, param).then( res => {
          if (res.code === 1) {
            this._storage.setSessionObject('user', res.data);
            this._storage.setSession('preference', this.newSetting);
            this._router.navigate(['/attache/personal']);
          }else {
            alert(res.msg);
          }
        });
      }
  }
}
